<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="highQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="dept" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="姓名" width="120" sortable>
			</el-table-column>
      <el-table-column prop="sn" label="编号" width="80" sortable>
      </el-table-column>
      <el-table-column prop="dirPath" label="上级部门层级ID" width="160" sortable>
      </el-table-column>
			<el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state == 0">正常</span>
          <span style="color: red" v-else-if="scope.row.state == -1">禁用</span>
          <span style="color: grey" v-else>未知</span>
        </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门管理员" width="120" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" v-perm="'dept:deleteById'" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--分页工具-->
			<el-pagination @size-change="handleSizeChange" :page-sizes="[5,10,15,20]" layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="myTitle" :visible.sync="addOrEditFormVisible" :close-on-click-modal="false">
      <el-form :model="addOrEditForm" label-width="80px" :rules="editFormRules" ref="addOrEditForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addOrEditForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="sn">
          <el-input v-model="addOrEditForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="addOrEditForm.state">
            <el-radio class="radio" :label="0">正常</el-radio>
            <el-radio class="radio" :label="-1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员">
          <!--
             :key   下拉列表行的唯一键 id
             :label  选中之后展示在下拉列表框中的值
             :value  选中之后绑定给模型层的
               ==============
                 value-key="id"  如果我们要传递对象给后端，这里一定增加value-key
                 会通过id去employees里面查找把整个employe对象转给后端
               ==============
          -->
          <el-select v-model="addOrEditForm.manager" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!--
          v-model 	选中项绑定值,即所选中项绑定给模型层的值
          :options  可选项数据源
          ==============================================
          checkStrictly   是否严格的遵守父子节点不互相关联
          value     指定选项的值为选项对象的某个属性值
          label     指定选项标签为选项对象的某个属性值
        -->
        <el-form-item label="上级部门">
          <el-cascader v-model="addOrEditForm.parent"
                       :options="deptTree"
                       :props="{
                                checkStrictly: true,
                                value:'id',
                                label:'name'
                                }"
                       clearable></el-cascader>
        </el-form-item>
      </el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addOrEditFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addOrEditSubmit" :loading="addOrEditLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
				filters: {
          keyword: ''
				},
				dept: [],
				total: 0,
        currentPage: 1,
        pageSize: 5,
        //列表忙等
				listLoading: false,
				sels: [],//列表选中列

				addOrEditFormVisible: false,//编辑界面是否显示
				addOrEditLoading: false,    //新增或修改操作，确认按钮忙等
				addOrEditFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
        myTitle:"",
        employees:[],
        deptTree:[],
				//编辑界面数据
				addOrEditForm: {
          id: null,
          name: "",
          sn: "",
          state: 0,
          manager: null,
          parent: null,
          dirPath:""
				}
			}
		},
		methods: {
      //高级查询后将当前页跳转至第一页
      highQuery(){
        this.currentPage = 1;
        this.getDept();
      },

      //当前页改变时
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDept();
			},
			//获取用户列表
			getDept() {
        //设置分页参数，json格式
				let para = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.filters.keyword
				};
				this.listLoading = true;

				//发送异步请求从后端拿数据
				this.$http.post("/dept",para)
				  .then(result=>{
				    //从回调参数中获取data数据
            var data = result.data;
            this.dept = data.rows;
            this.total = data.total;
            this.listLoading = false;
          })
          .catch(result=>{
            console.log(result);
            this.$message.error('系统繁忙，请稍后重试!!!');
          })
			},
			//删除
			handleDel: function (index, row) {
        //是否删除提示框
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {   //确定
					this.listLoading = true;
					//NProgress.start();
					this.$http.delete("/dept/"+row.id)
            .then(result=>{
              result = result.data;
              if (result.success==false){
                this.$message.error(result.message);
              }
              //删除成功后跳转至第一页
              this.currentPage = 1;
              this.getDept();
              this.listLoading = false;
              this.$message.success(result.message);
            })
            .catch(result=>{
              console.log(result);
              this.$message.error('系统繁忙，请稍后重试!!!');
            })
				}).catch(() => {  //取消

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        //在显示
        this.getDeptTree();
        this.myTitle="编辑";
				this.addOrEditFormVisible = true;
        //克隆  用于回显
				this.addOrEditForm = Object.assign({}, row);

				//回显上级部门
        let dirPath = this.addOrEditForm.dirPath;
        //当dirPath不会空时操作
        if(dirPath){//  "/2/5/8"
          let arry = dirPath.split("/");//  ["","2","5","8"]
          let parent = [];//[2,5]
          for(let i=1;i<arry.length-1;i++){
            parent.push(parseInt(arry[i]));
          }
          this.addOrEditForm.parent = parent;
        }
			},
			//显示新增界面
			handleAdd: function () {
        this.getDeptTree();
        this.myTitle="新增";
				this.addOrEditFormVisible = true;
        //重置表单
				this.addOrEditForm = {
          id: null,
          name: "",
          sn: "",
          state: 0,
          manager: null,
          parent: null,
          dirPath:""
				};
			},
			//新增或修改确认提交
			addOrEditSubmit: function () {
				this.$refs.addOrEditForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
						  //开启确认按钮忙等
							this.addOrEditLoading = true;
							let para = Object.assign({}, this.addOrEditForm);
              if(para.parent){//[2,7]   --   {"id":7}
                //将数组封装成对象形式，后端接受到parent对象后，mapper.xml中新增修改时直接调用parent.id的值
                para.parent = {"id":para.parent[para.parent.length -1]}
              }

              this.$http.put("/dept",para)
                  .then(result=>{
                    result = result.data;
                    if (result.success==false){
                      this.$message.error(result.message);
                    }
                    this.currentPage = 1;
                    this.addOrEditLoading = false;
                    this.addOrEditFormVisible = false;
                    this.$message.success(result.message);
                    this.getDept();
                  })
                  .catch(result=>{
                    console.log(result);
                    this.$message.error('系统繁忙，请稍后重试!!!');
                  })
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
          this.$http.patch("/dept",ids)
            .then(result=>{
              result = result.data;
              if (result.success==false){
                this.$message.error(result.message);
              }
              this.currentPage = 1;
              this.getDept();
              this.$message.success(result.message);
            })
            .catch(result=>{
              console.log(result);
              this.$message.error('系统繁忙，请稍后重试!!!');
            })
				}).catch(() => {

				});
			},
      getEmps(){
        this.$http.get("/emp")
          .then(result=>{
            //将查出的员工列表赋给模型层
            this.employees = result.data;
          })
      },
      getDeptTree(){
        this.$http.get("/dept/tree")
          .then(result=>{
            this.deptTree = result.data;
          })
      },
      handleSizeChange(size){
        this.pageSize = size;
        this.getDept();
      }
		},
		mounted() {
			this.getDept();
			//在页面加载的时候初始化employees模型层值
			this.getEmps();
		}
	}

</script>

<style scoped>

</style>